<template>
  <view class="health-page">
    <!-- 头部导航 -->
    <view class="header">
      <text class="page-title">健康信息</text>
    </view>
    
    <!-- 入住人选择 -->
    <view class="resident-selector">
      <scroll-view class="selector-scroll" scroll-x="true" show-scrollbar="false">
        <view 
          class="resident-item" 
          v-for="(person, index) in residents" 
          :key="index"
          :class="{ 'active': currentResident.id === person.id }"
          @tap="switchResident(person)"
        >
          <image class="resident-avatar" :src="person.avatar || '../../image/R.jpg'" mode="aspectFill"></image>
          <text class="resident-name">{{ person.name }}</text>
        </view>
        <view class="resident-item add-item" @tap="showAddElderPopup">
          <view class="add-avatar">
            <text class="iconfont">&#xe654;</text>
          </view>
          <text class="resident-name">添加</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 健康数据面板 -->
    <scroll-view class="health-content" scroll-y="true" enable-back-to-top="true" :scroll-anchoring="true">
      <!-- 数据概览卡片 -->
      <view class="overview-card">
        <view class="card-header">
          <text class="card-title">健康概览</text>
          <text class="last-update">上次更新: {{ formatDate(currentResident.lastUpdate) }}</text>
        </view>
        
        <view class="health-grid">
          <view class="health-item" @tap="showDetail('bloodPressure')">
            <view class="item-icon" :class="getStatusClass(currentResident.bloodPressure.status)">
              <text class="iconfont">&#xe611;</text>
            </view>
            <view class="item-data">
              <text class="item-name">血压</text>
              <text class="item-value">{{ currentResident.bloodPressure.value }}</text>
              <text class="item-unit">mmHg</text>
            </view>
          </view>
          
          <view class="health-item" @tap="showDetail('bloodSugar')">
            <view class="item-icon" :class="getStatusClass(currentResident.bloodSugar.status)">
              <text class="iconfont">&#xe60e;</text>
            </view>
            <view class="item-data">
              <text class="item-name">血糖</text>
              <text class="item-value">{{ currentResident.bloodSugar.value }}</text>
              <text class="item-unit">mmol/L</text>
            </view>
          </view>
          
          <view class="health-item" @tap="showDetail('bloodLipids')">
            <view class="item-icon" :class="getStatusClass(currentResident.bloodLipids.status)">
              <text class="iconfont">&#xe614;</text>
            </view>
            <view class="item-data">
              <text class="item-name">血脂</text>
              <text class="item-value">{{ currentResident.bloodLipids.value }}</text>
              <text class="item-unit">mmol/L</text>
            </view>
          </view>
          
          <view class="health-item" @tap="showDetail('uricAcid')">
            <view class="item-icon" :class="getStatusClass(currentResident.uricAcid.status)">
              <text class="iconfont">&#xe64a;</text>
            </view>
            <view class="item-data">
              <text class="item-name">尿酸</text>
              <text class="item-value">{{ currentResident.uricAcid.value }}</text>
              <text class="item-unit">μmol/L</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 历史记录卡片 -->
      <view class="history-card">
        <view class="card-header">
          <text class="card-title">历史记录</text>
          <text class="view-all" @tap="viewAllHistory">查看全部</text>
        </view>
        
        <view class="history-tabs">
          <view 
            class="tab-item" 
            v-for="(tab, index) in historyTabs" 
            :key="index"
            :class="{ 'active': currentTab === tab.id }"
            @tap="switchTab(tab.id)"
          >
            <text class="tab-text">{{ tab.name }}</text>
          </view>
        </view>
        
        <view class="history-list">
          <view class="empty-tip" v-if="historyRecords.length === 0">
            <text class="tip-text">暂无历史记录</text>
          </view>
          <view 
            class="history-item" 
            v-for="(record, index) in historyRecords" 
            :key="index"
            @tap="viewRecordDetail(record)"
          >
            <view class="record-date">
              <text class="date-day">{{ formatDay(record.date) }}</text>
              <text class="date-month">{{ formatMonth(record.date) }}</text>
            </view>
            <view class="record-content">
              <text class="record-value">{{ record.value }}</text>
              <text class="record-time">{{ formatTime(record.date) }}</text>
            </view>
            <view class="record-status" :class="getStatusClass(record.status)">
              <text class="status-text">{{ getStatusText(record.status) }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 入住人管理卡片 -->
      <view class="health-card elder-card">
        <view class="card-header">
          <view class="card-title">
            <text class="iconfont icon-elder">&#xe60d;</text>
            <text class="title-text">入住人管理</text>
          </view>
        </view>
        <view class="card-body">
          <view class="elder-empty" v-if="elderList.length === 0">
            <image src="/static/images/elder-empty.png" mode="aspectFit" class="empty-img"></image>
            <text class="empty-text">暂无入住人信息</text>
          </view>
          <view class="elder-list" v-else>
            <view class="elder-item" v-for="(item, index) in elderList" :key="index">
              <view class="elder-avatar">
                <image :src="item.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              </view>
              <view class="elder-info">
                <view class="elder-name">{{item.name}}</view>
                <view class="elder-detail">{{item.gender}} | {{item.age}}岁</view>
              </view>
              <view class="elder-actions">
                <view class="edit-btn" @tap="editElder(index)">
                  <text class="iconfont">&#xe62f;</text>
                </view>
                <view class="delete-btn" @tap="deleteElder(index)">
                  <text class="iconfont">&#xe6a7;</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部安全区域 -->
      <view class="safe-area-bottom"></view>
    </scroll-view>

    <!-- 添加入住人弹窗 -->
    <view class="add-elder-popup" v-if="showAddElder">
      <view class="popup-mask" @tap="hideAddElderPopup"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{isEditingElder ? '编辑入住人' : '添加入住人'}}</text>
          <view class="close-btn" @tap="hideAddElderPopup">
            <text class="iconfont">&#xe60e;</text>
          </view>
        </view>
        <scroll-view class="popup-body" scroll-y="true" enhanced="true" show-scrollbar="false">
          <!-- 头像选择 -->
          <view class="avatar-selector">
            <view class="avatar-preview" @tap="chooseAvatar">
              <image :src="elderForm.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              <view class="avatar-mask">
                <text class="iconfont">&#xe653;</text>
              </view>
            </view>
            <text class="avatar-tip">点击选择头像</text>
          </view>
          
          <!-- 表单内容 -->
          <view class="popup-form">
            <view class="form-item">
              <text class="form-label required">姓名</text>
              <input type="text" v-model="elderForm.name" placeholder="请输入姓名" class="form-input" maxlength="10" />
            </view>
            
            <view class="form-item">
              <text class="form-label required">身份证</text>
              <input type="idcard" v-model="elderForm.idCard" placeholder="请输入身份证号码" class="form-input" maxlength="18" />
            </view>
            
            <view class="form-item">
              <text class="form-label required">性别</text>
              <view class="gender-selector">
                <view 
                  class="gender-option" 
                  :class="{'selected': elderForm.gender === '男'}" 
                  @tap="elderForm.gender = '男'"
                >
                  <text class="gender-icon iconfont">&#xe630;</text>
                  <text class="gender-text">男</text>
                </view>
                <view 
                  class="gender-option" 
                  :class="{'selected': elderForm.gender === '女'}" 
                  @tap="elderForm.gender = '女'"
                >
                  <text class="gender-icon iconfont">&#xe631;</text>
                  <text class="gender-text">女</text>
                </view>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label required">出生日期</text>
              <picker 
                mode="date" 
                :value="elderForm.birthDate" 
                start="1920-01-01" 
                :end="today" 
                @change="onBirthDateChange" 
                class="date-picker"
              >
                <view class="picker-view">
                  <text class="picker-text">{{elderForm.birthDate || '请选择出生日期'}}</text>
                  <text class="iconfont">&#xe62d;</text>
                </view>
              </picker>
            </view>
            
            <view class="form-item">
              <text class="form-label">手机号码</text>
              <input type="number" v-model="elderForm.phone" placeholder="选填" class="form-input" maxlength="11" />
            </view>
            <view class="form-item">
              <text class="form-label required">账号与本人关系</text>
              <picker class="form-picker" :range="relationOptions" @change="handleRelationChange">
                <view class="picker-view">
                  <text class="picker-text">{{ elderForm.relation || '请选择关系' }}</text>
                  <text class="iconfont">&#xe62d;</text>
                </view>
              </picker>
            </view>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <view class="cancel-btn" @tap="hideAddElderPopup">取消</view>
          <view 
            class="confirm-btn" 
            :class="{'active': isElderFormValid}" 
            @tap="saveElder"
          >确认</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import useAuthCheck from '../../utils/authCheck';

// 引入权限校验
const { checkAuth } = useAuthCheck();

// 页面加载时检查登录状态
onMounted(() => {
  if (checkAuth()) {
    // 已登录，加载数据
    loadResidents();
  }
});

// 模拟入住人数据
const residents = ref([
  {
    id: 1,
    name: '张三',
    avatar: '../../image/R.jpg',
    lastUpdate: new Date(2023, 8, 15, 8, 30),
    bloodPressure: {
      value: '120/80',
      status: 'normal',
      history: [
        { date: new Date(2023, 8, 15, 8, 30), value: '120/80', status: 'normal' },
        { date: new Date(2023, 8, 14, 9, 15), value: '125/85', status: 'normal' },
        { date: new Date(2023, 8, 13, 7, 45), value: '130/90', status: 'warning' },
      ]
    },
    bloodSugar: {
      value: '5.4',
      status: 'normal',
      history: [
        { date: new Date(2023, 8, 15, 7, 0), value: '5.4', status: 'normal' },
        { date: new Date(2023, 8, 13, 7, 15), value: '5.6', status: 'normal' },
        { date: new Date(2023, 8, 11, 7, 30), value: '6.2', status: 'warning' },
      ]
    },
    bloodLipids: {
      value: '4.2',
      status: 'normal',
      history: [
        { date: new Date(2023, 8, 10, 8, 0), value: '4.2', status: 'normal' },
        { date: new Date(2023, 7, 15, 8, 45), value: '4.5', status: 'normal' },
      ]
    },
    uricAcid: {
      value: '320',
      status: 'normal',
      history: [
        { date: new Date(2023, 8, 12, 9, 0), value: '320', status: 'normal' },
        { date: new Date(2023, 7, 20, 8, 30), value: '350', status: 'normal' },
      ]
    }
  },
  {
    id: 2,
    name: '李四',
    avatar: '../../image/R.jpg',
    lastUpdate: new Date(2023, 8, 14, 9, 45),
    bloodPressure: {
      value: '135/90',
      status: 'warning',
      history: [
        { date: new Date(2023, 8, 14, 9, 45), value: '135/90', status: 'warning' },
        { date: new Date(2023, 8, 12, 8, 30), value: '130/88', status: 'normal' },
      ]
    },
    bloodSugar: {
      value: '6.1',
      status: 'warning',
      history: [
        { date: new Date(2023, 8, 14, 7, 30), value: '6.1', status: 'warning' },
        { date: new Date(2023, 8, 12, 7, 0), value: '5.8', status: 'normal' },
      ]
    },
    bloodLipids: {
      value: '5.1',
      status: 'warning',
      history: [
        { date: new Date(2023, 8, 10, 9, 0), value: '5.1', status: 'warning' },
      ]
    },
    uricAcid: {
      value: '410',
      status: 'warning',
      history: [
        { date: new Date(2023, 8, 8, 8, 15), value: '410', status: 'warning' },
      ]
    }
  }
]);

// 当前选择的入住人
const currentResident = ref(residents.value[0]);

// 历史记录选项卡
const historyTabs = [
  { id: 'bloodPressure', name: '血压' },
  { id: 'bloodSugar', name: '血糖' },
  { id: 'bloodLipids', name: '血脂' },
  { id: 'uricAcid', name: '尿酸' }
];

// 当前选中的选项卡
const currentTab = ref('bloodPressure');

// 根据当前选项卡获取历史记录
const historyRecords = computed(() => {
  return currentResident.value[currentTab.value].history || [];
});

// 加载入住人数据
const loadResidents = () => {
  // 实际项目中这里应该调用API获取数据
  console.log('加载入住人数据');
};

// 切换入住人
const switchResident = (person) => {
  currentResident.value = person;
};

// 显示详情
const showDetail = (type) => {
  switchTab(type);
  // 可以滚动到历史记录部分
  uni.createSelectorQuery()
    .select('.history-card')
    .boundingClientRect(data => {
      uni.pageScrollTo({
        scrollTop: data.top,
        duration: 300
      });
    })
    .exec();
};

// 新增入住人对象
const newResident = ref({
  name: '',
  idCard: '',
  gender: '男',
  birthDate: '',
  phone: '',
  relation: '',
  relationCode: ''
});

// 关系选项
const relationOptions = ['本人', '父亲', '母亲', '配偶', '其他'];

// 关系代码映射
const relationCodeMap = {
  '本人': 1,
  '父亲': 2,
  '母亲': 3,
  '配偶': 4,
  '其他': 5
};

// 处理关系选择器变化
const handleRelationChange = (e) => {
  const selectedRelation = relationOptions[e.detail.value];
  const relationCode = relationCodeMap[selectedRelation];
  const relationText = selectedRelation;
  
  // 保存关系文本和代码
  newResident.value.relation = relationText;
  newResident.relationCode = relationCode;
  
  elderForm.relation = relationText;
  elderForm.relationCode = relationCode;
  
  console.log('选择的关系代码:', relationCode, '关系文本:', relationText);
};

// 切换选项卡
const switchTab = (tabId) => {
  currentTab.value = tabId;
};

// 查看所有历史记录
const viewAllHistory = () => {
  uni.navigateTo({
    url: `/pages/health/history?residentId=${currentResident.value.id}&type=${currentTab.value}`
  });
};

// 查看记录详情
const viewRecordDetail = (record) => {
  // 可以传递记录ID跳转到详情页
  uni.navigateTo({
    url: `/pages/health/record-detail?type=${currentTab.value}&time=${record.date.getTime()}`
  });
};

// 获取状态对应的样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'normal':
      return 'status-normal';
    case 'warning':
      return 'status-warning';
    case 'danger':
      return 'status-danger';
    default:
      return '';
  }
};

// 获取状态对应的文本
const getStatusText = (status) => {
  switch (status) {
    case 'normal':
      return '正常';
    case 'warning':
      return '偏高';
    case 'danger':
      return '异常';
    default:
      return '未知';
  }
};

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return '暂无记录';
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 格式化日期为日
const formatDay = (date) => {
  if (!date) return '';
  return date.getDate().toString();
};

// 格式化日期为月
const formatMonth = (date) => {
  if (!date) return '';
  const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  return months[date.getMonth()];
};

// 格式化时间为 HH:MM
const formatTime = (date) => {
  if (!date) return '';
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 入住人管理相关
const elderList = ref([]);
const showAddElder = ref(false);
const isEditingElder = ref(false);
const editingElderIndex = ref(-1);
const today = formatDate(new Date());

// 入住人表单
const elderForm = reactive({
  avatar: '',
  name: '',
  idCard: '',
  gender: '男',
  birthDate: '',
  phone: '',
  relation: '',
  relationCode: ''
});

// 计算表单是否有效
const isElderFormValid = computed(() => {
  return elderForm.name && 
         isValidIdCard(elderForm.idCard) &&
         elderForm.gender && 
         elderForm.birthDate &&
         elderForm.relation; // 添加关系验证
});

// 显示添加入住人弹窗
const showAddElderPopup = () => {
  resetElderForm();
  isEditingElder.value = false;
  showAddElder.value = true;
};

// 隐藏添加入住人弹窗
const hideAddElderPopup = () => {
  showAddElder.value = false;
};

// 重置入住人表单
const resetElderForm = () => {
  Object.assign(elderForm, {
    avatar: '',
    name: '',
    idCard: '',
    gender: '男',
    birthDate: '',
    phone: '',
    relation: '',
    relationCode: ''
  });
  
  // 同步重置newResident
  Object.assign(newResident.value, {
    name: '',
    idCard: '',
    gender: '男',
    birthDate: '',
    phone: '',
    relation: '',
    relationCode: ''
  });
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      elderForm.avatar = res.tempFilePaths[0];
    }
  });
};

// 出生日期选择
const onBirthDateChange = (e) => {
  elderForm.birthDate = e.detail.value;
};

// 保存入住人信息
const saveElder = () => {
  if (!isElderFormValid.value) {
    if (!elderForm.name) {
      return uni.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
    }
    if (!isValidIdCard(elderForm.idCard)) {
      return uni.showToast({
        title: '请输入有效的身份证号',
        icon: 'none'
      });
    }
    if (!elderForm.birthDate) {
      return uni.showToast({
        title: '请选择出生日期',
        icon: 'none'
      });
    }
    if (!elderForm.relation) {
      return uni.showToast({
        title: '请选择账号与本人关系',
        icon: 'none'
      });
    }
    return;
  }
  
  // 根据身份证计算年龄
  const age = calculateAgeFromIdCard(elderForm.idCard);
  
  const elderInfo = {
    avatar: elderForm.avatar,
    name: elderForm.name,
    idCard: elderForm.idCard,
    gender: elderForm.gender,
    birthDate: elderForm.birthDate,
    phone: elderForm.phone || '',
    relation: elderForm.relation,
    relationCode: elderForm.relationCode, // 保存为数字
    age: age
  };
  
  if (isEditingElder.value && editingElderIndex.value >= 0) {
    // 编辑模式
    elderList.value[editingElderIndex.value] = elderInfo;
    
    // 同步更新residents中的对应数据
    const residentIndex = residents.value.findIndex(r => r.name === elderInfo.name);
    if (residentIndex !== -1) {
      residents.value[residentIndex].avatar = elderInfo.avatar || '../../image/R.jpg';
      residents.value[residentIndex].name = elderInfo.name;
    }
  } else {
    // 添加模式
    elderList.value.push(elderInfo);
    
    // 添加到residents列表，便于头像展示和切换
    const newResidentData = {
      id: residents.value.length + 1,
      name: elderInfo.name,
      avatar: elderInfo.avatar || '../../image/R.jpg',
      lastUpdate: new Date(),
      bloodPressure: {
        value: '--/--',
        status: 'normal',
        history: []
      },
      bloodSugar: {
        value: '--',
        status: 'normal',
        history: []
      },
      bloodLipids: {
        value: '--',
        status: 'normal',
        history: []
      },
      uricAcid: {
        value: '--',
        status: 'normal',
        history: []
      }
    };
    residents.value.push(newResidentData);
    
    // 自动切换到新添加的入住人
    currentResident.value = newResidentData;
  }
  
  // 保存到本地存储
  saveElderListToStorage();
  
  // 提示成功
  uni.showToast({
    title: isEditingElder.value ? '修改成功' : '添加成功',
    icon: 'success'
  });
  
  // 关闭弹窗
  hideAddElderPopup();
};

// 编辑入住人
const editElder = (index) => {
  const elder = elderList.value[index];
  if (elder) {
    Object.assign(elderForm, {
      avatar: elder.avatar,
      name: elder.name,
      idCard: elder.idCard,
      gender: elder.gender,
      birthDate: elder.birthDate,
      phone: elder.phone || '',
      relation: elder.relation || '',
      relationCode: elder.relationCode || ''
    });
    
    // 同步到newResident
    Object.assign(newResident.value, {
      name: elder.name,
      idCard: elder.idCard,
      gender: elder.gender,
      birthDate: elder.birthDate,
      phone: elder.phone || '',
      relation: elder.relation || '',
      relationCode: elder.relationCode || ''
    });
    
    isEditingElder.value = true;
    editingElderIndex.value = index;
    showAddElder.value = true;
  }
};

// 删除入住人
const deleteElder = (index) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该入住人信息吗？',
    success: (res) => {
      if (res.confirm) {
        const deletedElder = elderList.value[index];
        
        // 删除elderList中的数据
        elderList.value.splice(index, 1);
        
        // 同步删除residents中的对应数据
        const residentIndex = residents.value.findIndex(r => r.name === deletedElder.name);
        if (residentIndex !== -1) {
          residents.value.splice(residentIndex, 1);
          
          // 如果删除的是当前选中的入住人，则切换到第一个入住人
          if (currentResident.value.name === deletedElder.name && residents.value.length > 0) {
            currentResident.value = residents.value[0];
          }
        }
        
        saveElderListToStorage();
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      }
    }
  });
};

// 保存入住人列表到本地存储
const saveElderListToStorage = () => {
  try {
    uni.setStorageSync('elderOptions', JSON.stringify(elderList.value));
  } catch (e) {
    console.error('保存入住人数据失败', e);
  }
};

// 从本地存储加载入住人列表
const loadElderListFromStorage = () => {
  try {
    const storedElders = uni.getStorageSync('elderOptions');
    if (storedElders) {
      elderList.value = JSON.parse(storedElders);
    }
  } catch (e) {
    console.error('获取入住人数据失败', e);
  }
};

// 验证身份证号
const isValidIdCard = (idCard) => {
  // 简单验证，实际项目中应使用更严格的验证
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(idCard);
};

// 根据身份证计算年龄
const calculateAgeFromIdCard = (idCard) => {
  if (!isValidIdCard(idCard)) return 0;
  
  let birthYear, birthMonth, birthDay;
  if (idCard.length === 15) {
    birthYear = '19' + idCard.substring(6, 8);
    birthMonth = idCard.substring(8, 10);
    birthDay = idCard.substring(10, 12);
  } else {
    birthYear = idCard.substring(6, 10);
    birthMonth = idCard.substring(10, 12);
    birthDay = idCard.substring(12, 14);
  }
  
  const now = new Date();
  const birth = new Date(`${birthYear}-${birthMonth}-${birthDay}`);
  let age = now.getFullYear() - birth.getFullYear();
  
  // 如果今年的生日还没到，年龄减1
  if (now.getMonth() < birth.getMonth() - 1 || 
     (now.getMonth() === birth.getMonth() - 1 && now.getDate() < birth.getDate())) {
    age--;
  }
  
  return age;
};

// 页面初始化时加载入住人列表
onMounted(() => {
  loadElderListFromStorage();
  
  // 将elderList中的数据同步到residents列表
  if (elderList.value.length > 0) {
    elderList.value.forEach((elder, index) => {
      // 检查residents中是否已存在该入住人
      const existingIndex = residents.value.findIndex(r => r.name === elder.name);
      if (existingIndex === -1) {
        // 如果不存在，则添加
        residents.value.push({
          id: residents.value.length + 1,
          name: elder.name,
          avatar: elder.avatar || '../../image/R.jpg',
          lastUpdate: new Date(),
          bloodPressure: {
            value: '--/--',
            status: 'normal',
            history: []
          },
          bloodSugar: {
            value: '--',
            status: 'normal',
            history: []
          },
          bloodLipids: {
            value: '--',
            status: 'normal',
            history: []
          },
          uricAcid: {
            value: '--',
            status: 'normal',
            history: []
          }
        });
      }
    });
  }
});
</script>

<style lang="scss">
page {
  background-color: #f0f7f7;
  height: 100%;
}

.health-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  
  .header {
    padding: 15px 20px;
    background-color: #fff;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
    
    .page-title {
      font-size: 20px;
      font-weight: 600;
      color: #2c7873;
    }
  }
  
  .resident-selector {
    background-color: #fff;
    padding: 15px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
    
    .selector-scroll {
      white-space: nowrap;
      
      .resident-item {
        display: inline-flex;
        flex-direction: column;
        align-items: center;
        margin-right: 20px;
        vertical-align: top;
        
        &:last-child {
          margin-right: 0;
        }
        
        .resident-avatar, .add-avatar {
          width: 60px;
          height: 60px;
          border-radius: 30px;
          margin-bottom: 8px;
        }
        
        .resident-avatar {
          background-color: #f5f5f5;
          border: 2px solid rgba(195, 227, 227, 0.3);
        }
        
        .resident-name {
          font-size: 14px;
          color: #2c7873;
        }
        
        &.active {
          .resident-avatar {
            border-color: #c3e3e3;
          }
          
          .resident-name {
            color: #2c7873;
            font-weight: 600;
          }
        }
        
        &.add-item {
          .add-avatar {
            background: linear-gradient(135deg, #6FB3B8, #2c7873);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 10px rgba(44, 120, 115, 0.2);
            transition: all 0.3s ease;
            border: none;
            
            .iconfont {
              font-size: 28px;
              color: #fff;
            }
          }
          
          &:active .add-avatar {
            transform: scale(0.95);
            box-shadow: 0 2px 5px rgba(44, 120, 115, 0.15);
          }
        }
      }
    }
  }
  
  .health-content {
    flex: 1;
    padding: 15px 20px;
    box-sizing: border-box;
    height: 0; /* 重要：让flex-grow能够正常工作 */
    padding-bottom: 15px; /* 为底部添加足够空间 */
    
    // 卡片通用样式
    .overview-card, .history-card {
      background-color: #fff;
      border-radius: 15px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      margin-bottom: 20px;
      overflow: hidden;
      
      .card-header {
        padding: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        
        .card-title {
          font-size: 16px;
          font-weight: 600;
          color: #2c7873;
        }
        
        .view-all, .last-update {
          font-size: 12px;
          color: #2c7873;
        }
      }
    }
    
    // 健康概览
    .overview-card {
      .health-grid {
        display: flex;
        flex-wrap: wrap;
        padding: 10px;
        
        .health-item {
          width: 50%;
          padding: 10px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          
          .item-icon {
            width: 50px;
            height: 50px;
            border-radius: 25px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 15px;
            
            .iconfont {
              font-size: 25px;
              color: #fff;
            }
            
            &.status-normal {
              background-color: #c3e3e3;
            }
            
            &.status-warning {
              background-color: #f0a500;
            }
            
            &.status-danger {
              background-color: #e57373;
            }
          }
          
          .item-data {
            flex: 1;
            
            .item-name {
              font-size: 13px;
              color: #2c7873;
              display: block;
              margin-bottom: 4px;
            }
            
            .item-value {
              font-size: 18px;
              font-weight: 600;
              color: #2c7873;
            }
            
            .item-unit {
              font-size: 12px;
              color: #6FB3B8;
              margin-left: 4px;
            }
          }
        }
      }
    }
    
    // 历史记录
    .history-card {
      .history-tabs {
        display: flex;
        background-color: #f0f7f7;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        
        .tab-item {
          flex: 1;
          text-align: center;
          padding: 12px 0;
          position: relative;
          
          .tab-text {
            font-size: 14px;
            color: #2c7873;
          }
          
          &.active {
            .tab-text {
              color: #2c7873;
              font-weight: 600;
            }
            
            &::after {
              content: '';
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              width: 30px;
              height: 3px;
              background-color: #c3e3e3;
              border-radius: 1.5px;
            }
          }
        }
      }
      
      .history-list {
        padding: 10px 15px;
        
        .empty-tip {
          padding: 30px 0;
          text-align: center;
          
          .tip-text {
            font-size: 14px;
            color: #6FB3B8;
          }
        }
        
        .history-item {
          display: flex;
          align-items: center;
          padding: 15px 0;
          border-bottom: 1px solid rgba(0, 0, 0, 0.05);
          
          &:last-child {
            border-bottom: none;
          }
          
          .record-date {
            width: 50px;
            text-align: center;
            margin-right: 15px;
            
            .date-day {
              font-size: 20px;
              font-weight: 600;
              color: #2c7873;
              display: block;
            }
            
            .date-month {
              font-size: 12px;
              color: #2c7873;
            }
          }
          
          .record-content {
            flex: 1;
            
            .record-value {
              font-size: 16px;
              font-weight: 600;
              color: #2c7873;
              display: block;
              margin-bottom: 4px;
            }
            
            .record-time {
              font-size: 12px;
              color: #6FB3B8;
            }
          }
          
          .record-status {
            padding: 4px 10px;
            border-radius: 12px;
            
            .status-text {
              font-size: 12px;
              color: #fff;
            }
            
            &.status-normal {
              background-color: #c3e3e3;
            }
            
            &.status-warning {
              background-color: #f0a500;
            }
            
            &.status-danger {
              background-color: #e57373;
            }
          }
        }
      }
    }
  }
}

// 添加底部安全区域样式
.safe-area-bottom {
  height: 60px; /* tabBar的高度加上一些额外空间 */
}

/* 入住人管理卡片样式 */
.elder-card {
  .elder-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    
    .empty-img {
      width: 120px;
      height: 120px;
      margin-bottom: 10px;
    }
    
    .empty-text {
      font-size: 14px;
      color: #999;
      margin-bottom: 15px;
    }
  }
  
  .elder-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .elder-item {
    display: flex;
    align-items: center;
    padding: 12px;
    background-color: #f8fbfb;
    border-radius: 12px;
    position: relative;
    
    .elder-avatar {
      width: 50px;
      height: 50px;
      border-radius: 25px;
      overflow: hidden;
      margin-right: 12px;
      border: 1px solid #eee;
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    .elder-info {
      flex: 1;
      
      .elder-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }
      
      .elder-detail {
        font-size: 13px;
        color: #666;
      }
    }
    
    .elder-actions {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .edit-btn, .delete-btn {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        
        .iconfont {
          font-size: 18px;
        }
        
        &:active {
          background-color: rgba(0, 0, 0, 0.05);
        }
      }
      
      .edit-btn {
        .iconfont {
          color: #2c7873;
        }
      }
      
      .delete-btn {
        .iconfont {
          color: #ff6b6b;
        }
      }
    }
  }
}

/* 添加入住人弹窗样式 */
.add-elder-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
  }
  
  .popup-content {
    width: 90%;
    max-width: 340px;
    background-color: #fff;
    border-radius: 20px;
    position: relative;
    z-index: 2;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
    max-height: 85vh;
    margin: 20px 0;
    animation: popup-in 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    
    @keyframes popup-in {
      0% {
        opacity: 0;
        transform: scale(0.9);
      }
      100% {
        opacity: 1;
        transform: scale(1);
      }
    }
  }
  
  .popup-header {
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    flex-shrink: 0;
    background-color: #ffffff;
    
    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c7873;
    }
    
    .close-btn {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 16px;
      transition: all 0.2s ease;
      
      .iconfont {
        font-size: 20px;
        color: #2c7873;
      }
      
      &:active {
        background-color: rgba(0, 0, 0, 0.05);
        transform: scale(0.95);
      }
    }
  }
  
  .popup-body {
    flex: 1;
    padding: auto;
    overflow-y: auto;
    max-height: calc(85vh - 140px);
    background-color: #ffffff;
    
    .avatar-selector {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;
      
      .avatar-preview {
        width: 80px;
        height: 80px;
        border-radius: 40px;
        overflow: hidden;
        position: relative;
        margin-bottom: 10px;
        border: 2px solid #e8f4f2;
        box-shadow: 0 4px 12px rgba(44, 120, 115, 0.15);
        transition: all 0.3s ease;
        
        image {
          width: 100%;
          height: 100%;
          transition: transform 0.3s ease;
        }
        
        .avatar-mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(44, 120, 115, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: all 0.3s ease;
          
          .iconfont {
            font-size: 26px;
            color: #fff;
          }
        }
        
        &:active {
          transform: scale(0.95);
          
          .avatar-mask {
            opacity: 1;
          }
          
          image {
            transform: scale(1.05);
          }
        }
      }
      
      .avatar-tip {
        font-size: 14px;
        color: #2c7873;
        padding: 5px 12px;
        border-radius: 15px;
        background-color: #f0f7f7;
      }
    }
    
    .popup-form {
      padding: 0 5px;
      
      .form-item {
        margin-bottom: 16px;
        
        .form-label {
          font-size: 14px;
          font-weight: 500;
          color: #2c7873;
          margin-bottom: 8px;
          display: block;
          
          &.required:after {
            content: '*';
            color: #ff6b6b;
            margin-left: 4px;
          }
        }
        
        .form-input {
          width: 100%;
          height: 46px;
          background-color: #f8f8f8;
          border-radius: 12px;
          border: 1px solid #e8e8e8;
          padding: 0 14px;
          font-size: 15px;
          color: #333;
          box-sizing: border-box;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #2c7873;
            background-color: #f2f8f7;
            box-shadow: 0 0 0 3px rgba(44, 120, 115, 0.1);
          }
        }
        
        .gender-selector {
          display: flex;
          gap: 12px;
          
          .gender-option {
            flex: 1;
            height: 46px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            background-color: #f8f8f8;
            border: 1px solid #e8e8e8;
            border-radius: 12px;
            transition: all 0.3s ease;
            
            .gender-icon {
              font-size: 18px;
              color: #999;
              transition: all 0.3s ease;
            }
            
            .gender-text {
              font-size: 15px;
              color: #333;
              transition: all 0.3s ease;
            }
            
            &.selected {
              background-color: #e8f4f2;
              border-color: #2c7873;
              box-shadow: 0 3px 8px rgba(44, 120, 115, 0.15);
              
              .gender-icon, .gender-text {
                color: #2c7873;
                font-weight: 500;
              }
            }
            
            &:active {
              opacity: 0.8;
              transform: scale(0.98);
            }
          }
        }
        
        .date-picker, .form-picker {
          width: 100%;
          
          .picker-view {
            width: 100%;
            height: 46px;
            background-color: #f8f8f8;
            border-radius: 12px;
            border: 1px solid #e8e8e8;
            padding: 0 14px;
            font-size: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-sizing: border-box;
            transition: all 0.3s ease;
            
            .picker-text {
              color: #333;
              max-width: 80%;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .iconfont {
              font-size: 18px;
              color: #2c7873;
            }
            
            &:active {
              background-color: #f2f8f7;
              border-color: #2c7873;
              box-shadow: 0 0 0 3px rgba(44, 120, 115, 0.1);
            }
          }
        }
      }
    }
  }
  
  .popup-footer {
    display: flex;
    padding: 15px 20px;
    gap: 12px;
    border-top: 1px solid rgba(0, 0, 0, 0.06);
    flex-shrink: 0;
    background-color: #ffffff;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 46px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 500;
      border-radius: 12px;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.96);
      }
    }
    
    .cancel-btn {
      color: #2c7873;
      background-color: rgba(44, 120, 115, 0.1);
      border: 1px solid rgba(44, 120, 115, 0.2);
      
      &:active {
        background-color: rgba(44, 120, 115, 0.15);
      }
    }
    
    .confirm-btn {
      color: #fff;
      background-color: #999;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      
      &.active {
        background: linear-gradient(135deg, #6FB3B8, #2c7873);
        box-shadow: 0 5px 15px rgba(44, 120, 115, 0.3);
      }
      
      &:active {
        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.card-action {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background-color: #e8f4f2;
  border-radius: 20px;
  transition: all 0.3s ease;
  
  text {
    font-size: 13px;
    color: #2c7873;
    font-weight: 500;
  }
  
  .iconfont {
    margin-left: 4px;
    font-size: 14px;
  }
  
  &:active {
    transform: scale(0.96);
    background-color: #d8eae8;
  }
}

.card-title {
  display: flex;
  align-items: center;
  
  .icon-elder {
    font-size: 20px;
    color: #2c7873;
    margin-right: 8px;
  }
  
  .title-text {
    font-size: 16px;
    font-weight: 600;
    color: #2c7873;
  }
}

.form-picker {
  width: 100%;
  
  .picker-view {
    width: 100%;
    height: 44px;
    background-color: #f8f8f8;
    border-radius: 8px;
    border: 1px solid #e8e8e8;
    padding: 0 12px;
    font-size: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    transition: all 0.3s ease;
    
    .picker-text {
      color: #333;
    }
    
    .iconfont {
      font-size: 18px;
      color: #999;
    }
    
    &:active {
      background-color: #f2f8f7;
      border-color: #2c7873;
    }
  }
}
</style> 